/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.zhj.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

/**
 * 工具类
 * 
 * @author Vincent
 */
public class UTIL {

	/**
	 * 得到随机验证码
	 * 
	 * @param num
	 *            数量
	 * @return 验证码
	 */
	public static String getAuthCode(int num) {

		Random random = new Random();

		final String[] strs = {"A", "B", "C", "D", "E", "F", "G", "H", "J",
				"K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

		StringBuffer sbRandom = new StringBuffer();

		for (int i = 0; i < num; i++) {
			sbRandom.append(strs[random.nextInt(strs.length)]);
		}

		return sbRandom.toString();
	}

	/**
	 * 获得验证码图片
	 * 
	 * @param authCode
	 *            验证码
	 * @return
	 */
	public static BufferedImage getCodeImage(String authCode) {

		int width = 80;
		int height = 25;

		Random random = new Random();

		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

		Graphics2D g = image.createGraphics();

		Color c1 = Color.black;

		Color c2 = Color.white;

		g.setColor(c1);
		g.fillRect(0, 0, width, height);

		Font font = new Font("Times New Roman", Font.BOLD, 18);
		g.setFont(font);
		g.setColor(c2);

		for (int i = 0; i < 50; i++) {
			int x0 = random.nextInt(width);
			int y0 = random.nextInt(height);
			g.drawRect(x0, y0, 1, 1);
		}
		g.setColor(Color.white);
		g.drawString(authCode, 0, 20);

		return image;
	}

	/**
	 * 获取UUID
	 * 
	 * @return
	 */
	public static String getUUID() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}

	/**
	 * 获取项目根路径
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return
	 */
	public static String getRootPath() {
		String path = getRequest().getRequestURL().toString();
		int index = path.lastIndexOf("/");
		path = path.substring(0, index + 1);
		return path;
	}

	/**
	 * 读取properties文件
	 * 
	 * @param filePath
	 *            路径
	 * @param key
	 *            key值
	 * @return
	 * @throws IOException
	 */
	public static String readProperties(String filePath, String key) {
		Properties props = new Properties();
		String path = UTIL.class.getResource("").getPath().toString() + filePath;
		path = path.replaceFirst("%20", " ");
		try {
			InputStream in = new BufferedInputStream(new FileInputStream(path));
			props.load(in);
			String value = props.getProperty(key);
			return value;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * MD5加密
	 * 
	 * @param strObj
	 *            字符串
	 * @return 加密字符串
	 */
	public static String MD5(String strObj) {

		String resultString = null;
		try {
			resultString = new String(strObj);
			MessageDigest md = MessageDigest.getInstance("MD5");

			resultString = byteToString(md.digest(strObj.getBytes()));
		} catch (NoSuchAlgorithmException ex) {
			ex.printStackTrace();
		}
		return resultString;
	}

	// 转换字节数组为16进制字串

	private static String byteToString(byte[] bByte) {
		StringBuilder sBuffer = new StringBuilder();
		for (int i = 0; i < bByte.length; i++) {
			sBuffer.append(byteToArrayString(bByte[i]));
		}
		return sBuffer.toString();
	}

	// 返回形式为数字跟字符串

	private static String byteToArrayString(byte bByte) {
		final String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
		int iRet = bByte;
		if (iRet < 0) {
			iRet += 256;
		}
		int iD1 = iRet / 16;
		int iD2 = iRet % 16;
		return strDigits[iD1] + strDigits[iD2];
	}

	/**
	 * 发送邮件
	 * 
	 * @param email
	 *            收件人地址
	 * @param content
	 *            邮件内容
	 * @param subject
	 *            邮件主题
	 * @param username
	 *            邮箱账号
	 * @param password
	 *            邮箱密码
	 */
	public static boolean sendEmail(String username, String password, String email, String content, String subject) {
		Properties props = new Properties();
		/* 验证 */
		props.setProperty("mail.smtp.auth", "true");
		/* 调试 */
		props.setProperty("mail.debug", "true");
		/* 传输协议 */
		props.setProperty("mail.transport.protocol", "smtp");
		/* 主机 */
		props.setProperty("mail.host", "smtp.163.com");
		/* 用户名和密码封装 */
		Authenticator auth = new WghAuthenticator(username, password);
		Session session = Session.getInstance(props, auth);
		Message message = new MimeMessage(session);
		/* 发送人 */
		String nick = "唐佳论坛";
		try {
			nick = javax.mail.internet.MimeUtility.encodeText("唐佳论坛");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		try {
			InternetAddress address = new InternetAddress(nick + "<TangjiaForum@163.com>");
			message.setFrom(address);
			message.setContent(content, "text/html;charset=utf-8");
			message.setSubject(subject);
			/* 收件人 */
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
			Transport.send(message);
		} catch (MessagingException e) {
			return false;
		}
		return true;
	}
	
	public static HttpServletRequest getRequest(){
		return ServletActionContext.getRequest();
	}
	public static HttpServletResponse getResponse(){
		return ServletActionContext.getResponse();
	}
	
}
